import uuid

from fastapi import FastAPI, HTTPException, Request
from loguru import logger
from starlette.responses import JSONResponse
from starlette.staticfiles import StaticFiles

from ocr_http.handler.inference import router as api_router, InferenceResponse
from ocr_http.ocr_exception import NoSupportException
from utils.log import setup_logging

setup_logging()

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
app.include_router(api_router, prefix="/api")


@app.middleware("http")
async def log_url(request: Request, call_next):
    request_id = request.headers.get("request_id")
    if not request_id:
        request_id = str(uuid.uuid4())
    with logger.contextualize(request_id=str(request_id)):
        logger.info(f"request.url = {request.url}")
        response = await call_next(request)
        return response


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    logger.error(exc)
    return JSONResponse(
        content={"code": exc.status_code, "message": exc.detail},
    )


@app.exception_handler(NoSupportException)
async def no_support_exception_handler(request: Request, exc: NoSupportException):
    logger.error(exc)
    return JSONResponse(
        content=InferenceResponse(data={"class_id": "others", "ocr_result": {}}).dict(),
    )


@app.exception_handler(Exception)
async def exception_handler(request: Request, exc: Exception):
    logger.error(exc)
    return JSONResponse(
        content={"code": 500, "message": exc.__str__()},
    )
